package com.wxs.common.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wxs.common.dao.RoleGroupMapper;
import com.wxs.common.dao.UserMapper;
import com.wxs.common.pojo.RoleGroup;
import com.wxs.common.pojo.User;
import com.wxs.common.service.RoleGroupService;
import com.wxs.common.utils.DataGridModel;
import com.wxs.common.utils.DataResult;

/**
 * 角色组
 * 
 * @author admin
 *
 */
@Service
public class RoleGroupServiceImpl implements RoleGroupService {

	@Autowired
	private RoleGroupMapper roleGroupMapper;
	@Autowired
	private UserMapper userMapper;

	@Override
	public DataResult queryPage(String name, Boolean enabled, DataGridModel dgm) {
		PageHelper.startPage(dgm.getPage(), dgm.getLimit());
		List<RoleGroup> list = roleGroupMapper.list(name, enabled);
		PageInfo<RoleGroup> pinfo = new PageInfo<RoleGroup>(list);
		return new DataResult(list, pinfo.getTotal());
	}

	@Override
	public RoleGroup findById(Integer id) {
		return roleGroupMapper.selectByPrimaryKey(id);
	}

	@Override
	public int saveEdit(RoleGroup rolegroup) {
		return roleGroupMapper.updateByPrimaryKeySelective(rolegroup);
	}

	@Override
	public int saveAdd(RoleGroup rolegroup) {
		return roleGroupMapper.insertSelective(rolegroup);
	}

	@Override
	public Boolean checkName(String name, Integer id) {
		List<RoleGroup> roleGroups = roleGroupMapper.list(name, null);
		if (roleGroups == null || roleGroups.isEmpty()) {
			return false;
		} else {
			RoleGroup roleGroup = roleGroups.get(0);
			if (id == null) {
				return true;
			} else if (roleGroup.getId().equals(Integer.valueOf(id))) {
				return false;
			} else {
				return true;
			}
		}
	}

	@Override
	public int deleteById(Integer id) {
		List<User> users = userMapper.listByRoleGroupId(id);
		if (users != null && !users.isEmpty()) {
			throw new RuntimeException("当前角色组使用中，无法删除！");
		}
		roleGroupMapper.deleteRolegroup_Role(id);// 删除关联数据
		return roleGroupMapper.deleteByPrimaryKey(id);
	}

	@Override
	public int saveRoles(String[] roleids, Integer role_group_id) {
		roleGroupMapper.deleteRolegroup_Role(role_group_id);
		if (roleids.length > 0) {
			return roleGroupMapper.saveRolegroup_Role(roleids, role_group_id);
		}
		return 0;
	}

	@Override
	public List<RoleGroup> listAll() {
		return roleGroupMapper.list(null, null);
	}

}
